package com.kstech.exccheck.view.check;

import android.content.Intent;
import android.os.Bundle;

import java.util.List;
import android.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.kstech.exccheck.R;
import com.kstech.exccheck.config.vo.DeviceVO;
import com.kstech.exccheck.config.vo.SubDeviceVO;
import com.kstech.exccheck.db.CheckRecordDao;
import com.kstech.exccheck.exception.ExcException;
import com.kstech.exccheck.util.AppContext;
import com.kstech.exccheck.util.SystemUtil;
import com.kstech.exccheck.view.BaseActivity;

/**
 * 新建检测记录界面
 */
public class CreateCheckRecordActivity extends BaseActivity {

    // 机型表格与子机型表格
    private TableLayout deviceTableLayoutId, subDeviceTableLayoutId;

    // 被选中的机型与子机型单元格
    private LinearLayout selectedColumlayout, selectedSubColumlayout;

    private Button btnSureId, btnExitId;

    private EditText excIdET;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_check_record);

        // 初始化菜单，传入参数，设置子标题
        initMenu("---  新建检测");

        // 点击任意位置收键盘
        SystemUtil.setHideSoftKeyBoardListener(CreateCheckRecordActivity.this,
                R.id.activityNewCreate);

        // 初始化视图组件
        initViewComp();

        // 机型表格布局
        setDeviceLayout();

    }

    /**
     * 初始化视图组件
     */
    private void initViewComp() {
        deviceTableLayoutId = (TableLayout) findViewById(R.id.deviceTableLayoutId);
        subDeviceTableLayoutId = (TableLayout) findViewById(R.id.subDeviceTableLayoutId);
        btnSureId = (Button) findViewById(R.id.btnSureId);
        btnSureId.setOnClickListener(btnSureIdListener);
        btnExitId = (Button) findViewById(R.id.btnExitId);
        btnExitId.setOnClickListener(btnExitIdListener);
        excIdET = (EditText) findViewById(R.id.excIdET);
    }

    /**
     * 设置机型表格布局
     */
    private void setDeviceLayout() {
        final List<DeviceVO> deviceList = AppContext.getResConfig()
                .getDeviceList();
        // 整行数
        int whole = deviceList.size() / 3;
        // 余数
        int remain = deviceList.size() % 3;
        // 总行数
        int trTotal = remain == 0 ? whole : whole + 1;

        for (int i = 0; i < trTotal; i++) {
            TableRow tr = new TableRow(this);
            tr.setLayoutParams(new TableLayout.LayoutParams(
                    TableLayout.LayoutParams.MATCH_PARENT,
                    TableLayout.LayoutParams.WRAP_CONTENT));
            tr.setOrientation(LinearLayout.HORIZONTAL);
            tr.setDividerDrawable(getDrawable(R.drawable.table_h_divider));
            tr.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
            for (int j = 0; i == trTotal - 1 && remain != 0 ? j < remain
                    : j < 3; j++) {
                // 创建列单元格
                final LinearLayout columlayout = createColumCell(deviceList
                        .get(3 * i + j).getDeviceId(), deviceList
                        .get(3 * i + j).getDeviceName());
                tr.addView(columlayout);
                // 单元格机型下的子机型数据
                List<SubDeviceVO> subList = deviceList.get(3 * i + j)
                        .getSubDeviceList();
                // 监听机型列单元格点击事件
                setColumListener(columlayout, subList);
            }
            deviceTableLayoutId.addView(tr);
        }
    }

    /**
     * 监听机型单元格列点击事件
     *
     * @param columlayout
     * @param subList
     */
    private void setColumListener(final LinearLayout columlayout,
                                  final List<SubDeviceVO> subList) {
        columlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (selectedColumlayout != null) {
                    // 重置上一个机型，取消选中状态
                    ((TextView) selectedColumlayout.getChildAt(0))
                            .setTextColor(getResources().getColor(
                                    R.color.deviceTextColor));
                    selectedColumlayout.getChildAt(1).setVisibility(View.GONE);
                }
                selectedColumlayout = columlayout;
                // 设置当前点击机型被选中
                ((TextView) columlayout.getChildAt(0))
                        .setTextColor(getResources().getColor(
                                R.color.deviceSecectedTextColor));
                columlayout.getChildAt(1).setVisibility(View.VISIBLE);

                selectedSubColumlayout = null;
                // 设置子机型区域布局
                setSubDeviceLayout(subList);
            }

            private void setSubDeviceLayout(List<SubDeviceVO> subList) {
                // 移除所有子机型区域的视图
                subDeviceTableLayoutId.removeAllViews();

                // 重新加载子机型区域视图
                for (int k = 0; k < subList.size(); k++) {
                    TableRow tr = new TableRow(CreateCheckRecordActivity.this);
                    tr.setLayoutParams(new TableLayout.LayoutParams(
                            TableLayout.LayoutParams.MATCH_PARENT,
                            TableLayout.LayoutParams.WRAP_CONTENT));
                    tr.setOrientation(LinearLayout.HORIZONTAL);
                    tr.setDividerDrawable(getDrawable(R.drawable.table_h_divider));
                    tr.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);

                    final LinearLayout columlayout = createColumCell(subList
                            .get(k).getSubDevId(), subList.get(k)
                            .getSubDevName());

                    tr.addView(columlayout);

                    // 监听子机型点击事件
                    columlayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            if (selectedSubColumlayout != null) {
                                // 重置上一个机型，取消选中状态
                                ((TextView) selectedSubColumlayout
                                        .getChildAt(0))
                                        .setTextColor(getResources().getColor(
                                                R.color.deviceTextColor));
                                selectedSubColumlayout.getChildAt(1)
                                        .setVisibility(View.GONE);
                            }
                            selectedSubColumlayout = columlayout;
                            // 设置当前点击机型被选中
                            ((TextView) columlayout.getChildAt(0))
                                    .setTextColor(getResources().getColor(
                                            R.color.deviceSecectedTextColor));
                            columlayout.getChildAt(1).setVisibility(
                                    View.VISIBLE);
                        }
                    });

                    subDeviceTableLayoutId.addView(tr);
                }
            }

        });
    }

    /**
     * 创建列单元格
     *
     * @param id
     *            ,name
     * @return
     */
    private LinearLayout createColumCell(String id, String name) {
        final LinearLayout columlayout = new LinearLayout(this);
        columlayout.setLayoutParams(new TableRow.LayoutParams(0,
                TableRow.LayoutParams.WRAP_CONTENT, 1));
        columlayout.setOrientation(LinearLayout.HORIZONTAL);

        TextView excNameTV = new TextView(this);
        excNameTV.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 0.99f));
        excNameTV.setText(name);
        excNameTV.setTextSize(20);
        excNameTV.setPadding(15, 20, 15, 20);
        excNameTV.setGravity(Gravity.CENTER);
        excNameTV
                .setTextColor(getResources().getColor(R.color.deviceTextColor));

        LinearLayout imagelayout = new LinearLayout(this);
        imagelayout.setLayoutParams(new TableRow.LayoutParams(
                TableRow.LayoutParams.WRAP_CONTENT,
                TableRow.LayoutParams.WRAP_CONTENT));
        imagelayout.setGravity(Gravity.BOTTOM);
        imagelayout.setPadding(0, 55, 0, 0);
        ImageView iv = new ImageView(this);
        iv.setLayoutParams(new LinearLayout.LayoutParams(25, 25, 0.01f));
        iv.setBackground(getDrawable(R.drawable.selected_machine));
        imagelayout.addView(iv);
        imagelayout.setVisibility(View.GONE);

        TextView excIdTV = new TextView(this);
        excIdTV.setText(id);
        excIdTV.setVisibility(View.GONE);

        columlayout.addView(excNameTV);
        columlayout.addView(imagelayout);
        columlayout.addView(excIdTV);

        return columlayout;
    }

    /**
     * The Btn exit id listener.
     */
// 退出按钮监听事件
    View.OnClickListener btnExitIdListener = new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // 直接结束当前activity的生命周期
            finish();
        }
    };

    /**
     * The Btn sure id listener.
     */
// 确定按钮监听事件
    View.OnClickListener btnSureIdListener = new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // 校验参数
            if (validate()) {
                // 根据用户选择，新建机型
                String deviceId = ((TextView) selectedColumlayout.getChildAt(2))
                        .getText().toString();
                String subDeviceId = "";
                String subDeviceName = "";
                if (null != selectedSubColumlayout) {
                    subDeviceId = ((TextView) selectedSubColumlayout
                            .getChildAt(2)).getText().toString();
                    subDeviceName = ((TextView) selectedSubColumlayout
                            .getChildAt(0)).getText().toString();
                }

                try {
                    AppContext.loadDeviceModelFile(deviceId, subDeviceId);
                } catch (ExcException excException) {
                    Toast.makeText(AppContext.context, excException.getErrorMsg(), Toast.LENGTH_SHORT).show();
                    Log.e("AdminIndexActivity", excException.getErrorMsg());
                    return;
                }

                // 插入 检验记录表
                CheckRecordDao.addCheckRecord(excIdET.getText().toString(),
                        deviceId,
                        ((TextView) selectedColumlayout.getChildAt(0))
                                .getText().toString(), subDeviceId,
                        subDeviceName);

                Toast.makeText(CreateCheckRecordActivity.this,
                        R.string.saveSuccess, Toast.LENGTH_LONG).show();

                // 添加给AdminIndexActivity的返回值，并设置resultCode
                Intent intent = new Intent();
                intent.putExtra("deviceName", ((TextView) selectedColumlayout
                        .getChildAt(0)).getText().toString());
                intent.putExtra(
                        "subdeviceName",
                        null != selectedSubColumlayout ? ((TextView) selectedSubColumlayout
                                .getChildAt(0)).getText().toString() : null);
                intent.putExtra("excId", excIdET.getText().toString());
                setResult(RESULT_OK, intent);
                finish();
            }
        }

        private boolean validate() {
            // 判断机型与挖掘机出厂编号是否为空
            if (null == selectedColumlayout) {
                new AlertDialog.Builder(CreateCheckRecordActivity.this)
                        .setMessage(R.string.pleaseSelectedDevice)
                        .setNeutralButton(R.string.str_ok, null).show();
                return false;
            }
            String excId = excIdET.getText().toString().trim();
            if ("".equals(excId)) {
                new AlertDialog.Builder(CreateCheckRecordActivity.this)
                        .setMessage(R.string.pleaseInputExcId)
                        .setNeutralButton(R.string.str_ok, null).show();
                return false;
            }
            if (null != CheckRecordDao.findCheckRecordByExcId(excId)) {
                new AlertDialog.Builder(CreateCheckRecordActivity.this)
                        .setMessage(R.string.excIdIsExist)
                        .setNeutralButton(R.string.str_ok, null).show();
                return false;
            }
            return true;
        }
    };
}
